package quotation.web.wx.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import quotation.exception.BusinessException;
import quotation.web.wx.service.WXService;

/**
 * @author lyx
 * @date 2025/2/19
 */
@Service
@Slf4j
public class WXServiceImpl implements WXService {

    //js_code
    public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code";

    // TODO: 2025/2/19 补充开发者信息
    public static String APPID = "appid";

    public static final String SECRET = "secret";


    @Override
    public String getOpenId(String code) {


        String url = StrUtil.format(ACCESS_TOKEN_URL, APPID, SECRET, code);
        String body = HttpUtil.createGet(url)
                .execute()
                .charset("utf-8")
                .body();

        JSONObject responseJsonObject = JSONUtil.parseObj(body);
        if (ObjectUtil.isNull(responseJsonObject)) {
            throw new BusinessException("响应异常:获取信息为空!");
        }
        String errmsg = responseJsonObject.getStr("errmsg");
        if (StrUtil.isNotEmpty(errmsg)) {
            throw new BusinessException(errmsg);
        }

        String openId = responseJsonObject.getStr("openid");

        return openId;
    }
}
